import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
console.log('我是环境变量', process.env)
const request = axios.create({
  baseURL: `https://api-hmzs.itheima.net${process.env.VUE_APP_BASE_URL}`,
  timeout: 5000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 提示用户报错
    Message.error(error.response.data.msg || '接口错误')

    // 如果错误码是401 需要跳转到登录页
    if (error.response.status === 401) {
      store.commit('user/clearUserInfo')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request
